<template>
  <div class="content">
    <!-- 流程进度 -->
    <div class="process">
      <div class="title">流程进度</div>
      <el-steps v-if="isregisterApprove" :active="activeStep" finish-status="success">
        <el-step v-for="(item, index) in registerSteps" :key="index" :title="item.title"
          :description="item.description"></el-step>
      </el-steps>
      <el-steps v-else :active="activeStep" finish-status="success">
        <el-step v-for="(item, index) in knowledgeSteps" :key="index" :title="item.title"
          :description="item.description"></el-step>
      </el-steps>
    </div>

    <!-- 需求详情 -->
    <div class="detail">
      <!-- 注册审批 -->
      <div class="title">需求详情</div>
      <el-form v-if="isregisterApprove" :model="form" label-width="100px">
        <el-form-item label="标题">
          <el-input disabled v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="发起人">
          <el-input disabled v-model="form.f0602"></el-input>
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input disabled v-model="form.f0617"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input disabled v-model="form.f0604"></el-input>
        </el-form-item>
      </el-form>
      <!-- 知识库上传审批 -->
      <el-form v-else label-width="100px">
        <el-form-item label="标题">
          <el-input disabled v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="上传人">
          <el-input disabled v-model="form.f2102"></el-input>
        </el-form-item>
        <el-form-item label="附件信息">
          <div v-if="form.content && form.content.length > 0">
            <el-tag v-for="(item, index) in form.content" :key="index" @click="handlePreview(item)"
              style="margin-right: 10px; cursor: pointer;">
              {{ item }}
            </el-tag>
          </div>
          <div v-else style="color: #999;">
            无附件
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 受理记录 -->
    <div class="record">
      <div class="title">受理记录</div>
      <el-table :data="records">
        <el-table-column :flex="1" prop="status" label="状态" minWidth="25%">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">{{ scope.row.status === 0 ? '成功' : '失败'
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :flex="1" prop="department" label="环节名称" minWidth="25%"></el-table-column>
        <el-table-column :flex="1" prop="person" label="经办人" minWidth="25%"></el-table-column>
        <el-table-column :flex="1" prop="receiveTime" label="完成时间" minWidth="25%"></el-table-column>
      </el-table>
    </div>
    <div v-loading="loading" style="margin-top: 20px; float: right;">
      <el-button v-if="!isregisterApprove" type="primary" @click="handleSave">采纳</el-button>
      <el-button v-else type="primary" @click="handleSubmit">通过</el-button>
      <el-button v-if="!isregisterApprove" @click="handleSaveOUT" type="danger">终止</el-button>
      <el-button v-else type="danger" @click="handleReject">驳回</el-button>
      <el-button v-if="!isregisterApprove" @click="download" type="primary">文件下载</el-button>
    </div>
  </div>
</template>

<script>
import tab from '@/plugins/tab';
import { getProcessDetail, getUserInfo, userRegister, userRegisterReject, knowledgeUpload, knowledgeUploadReject } from '@/api/t06/t06';
import { getT09History } from "@/api/knowledge_manage/T09";
import { exportT09 } from "@/api/T09/T09";
export default {
  name: 'ProcessApprovalDetail',
  mixins: [tab],
  data() {
    return {
      loading: false,
      // 流程进度当前进行到第几环节
      activeStep: 3,
      // 审批
      isregisterApprove: true,
      // 注册审批流程
      registerSteps: [
        { title: '发起认证', description: '' },
        { title: '管理员审批', description: '' },
        { title: '完成', description: '' },
      ],
      // 知识库审批流程
      knowledgeSteps: [
        { title: '知识库上传', description: '' },
        { title: '管理员审批', description: '' },
        { title: '完成', description: '' },
      ],
      form: {
        title: '用户注册审批',
        category: 'Bug类',
        reporter: '香香智',
        f0602: '', // 用户名
        f0617: '', // 部门名称
        f0604: '', // 电话号码
        // 知识库上传审批
        f2101: '',// 上传人id
        f2102: '',// 上传人
        f2106: '',// 附件id
        content: [], // 附件信息
      },
      records: [
        { status: '', department: '', person: '', receiveTime: '2025-01-03 09:56:02', completeTime: '2025-01-03 09:58:00' },
      ],
      id: '',
      userInfo: {} // 注册用户信息
    };
  },
  async created() {
    this.id = this.$route.params.id;
    getUserInfo(this.id).then(res => {
      if (res.data) {
        this.userInfo = res.data
        this.form.f0602 = res.data.f0602
        this.form.f0617 = res.data.f0617
        this.form.f0604 = res.data.f0604
      }
      // this.form = res.data
    })
    await getProcessDetail(this.id).then(res => {
      this.registerSteps = this.registerSteps.map((step, index) => {
        // 从 res.data 中获取对应的 description 值
        const newDescription = res.data[index]?.f2406 || step.description;
        // 保留原始对象的其他字段，仅替换 description
        return {
          ...step,
          description: newDescription
        };
      });
      this.records = res.data.map((item, index) => {
        // 从 res.data 中获取对应的 description 值
        const newStatus = item.f2403
        const newDepartment = item.f2404 || this.records[index].department;
        const newPerson = item.f2402 || this.records[index].person;
        const newReceiveTime = item.f2406 || this.records[index].receiveTime;
        console.log('status', newStatus);
        // 保留原始对象的其他字段，仅替换 description
        // 保留原始对象的其他字段，仅替换 description
        return {
          status: newStatus,
          department: newDepartment,
          person: newPerson,
          receiveTime: newReceiveTime
        };
      });
      this.isregisterApprove = res.data[0].f2407 === 0;
      this.form.title = this.isregisterApprove === true ? '用户注册审批' : '知识库上传审批';
      this.activeStep = res.data[0].f2404 === '审批提交' || '审核提交' ? 1 : 2;
      console.log('records', this.records);
    })
    if (!this.isregisterApprove) {
      getT09History(this.id).then(res => {
        this.form.f2101 = res.data.f2101
        this.form.f2102 = res.data.f2102
        this.form.f2106 = res.data.f2106
        this.form.content = res.data.t09List.map(item => {
          return item.f0902;
        })
      })
    }
  },
  methods: {
    handlePreview(file) {
      window.open(`http://47.121.118.149:9000/buck1/${file}`, '_blank');
    },
    handleRemove(file, fileList) {
      console.log('Remove:', file, fileList);
    },
    handleSubmit() {
      this.$confirm('确定要提交审批吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userRegister([this.userInfo.f0601]).then(res => {
          this.$message({
            type: 'success',
            message: '提交成功!'
          });
          this.$router.push(`/approve`)
          this.$tab.closeOpenPage(); // 关闭当前页面
        })
      })
    },
    handleReject() {
      this.$confirm('确定要驳回吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userRegisterReject([this.userInfo.f0601]).then(res => {
          this.$message({
            type: 'success',
            message: '驳回成功!'
          });
          this.$router.push(`/approve`)
          this.$tab.closeOpenPage(); // 关闭当前页面
        })
      })
    },
    handleSave() {
      this.$confirm('确定要采纳审批吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        knowledgeUpload(this.form.f2101).then(res => {
          this.$message({
            type: 'success',
            message: '提交成功!'
          });
          this.$router.push('/ProcessApproval')
          this.$tab.closeOpenPage(); // 关闭当前页面
        })
      })
    },
    handleSaveOUT() {
      this.$confirm('确定要终止吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        knowledgeUploadReject(this.form.f2101).then(res => {
          this.$message({
            type: 'success',
            message: '终止成功!'
          });
          this.$router.push('/ProcessApproval')
          this.$tab.closeOpenPage(); // 关闭当前页面
        })
      })
    },
    download() {
      this.loading = true;
      const ids = this.form.f2106
      // console.log(ids)
       exportT09(ids,
        {
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
          },
        }).then(res => {
          console.log(111, res.data)
          let filename = '知识库';
          const url = window['URL'].createObjectURL(res);
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = filename; // 确保文件名与后端设置的一致
          document.body.appendChild(a);
          a.click();
          window['URL'].revokeObjectURL(url);
          document.body.removeChild(a);
        }).finally(() => {
          this.loading = false;
        })
    },
  }
};
</script>

<style scoped lang="scss">
.content {
  margin: 20px;
  .title {
    padding: 5px;
    background: #f0f7ff;
    text-align: start;
    font-size: 16px;
    color: black;
    margin-bottom: 20px;
  }
  .process{
    padding: 0 10px;
    margin-bottom: 20px
  }
}
.el-upload__tip {
  font-size: 12px;
  color: #999;
}
</style>
